import io from 'socket.io-client';

const socket = io.connect('http://localhost:8000/my-room');


const interval = 100;  //消息时间间隔
const num = 200;   //每次返回数据区间


//开始订阅聊天消息
function subscribe(userName, cb) {
    let list = []
    socket.on('message', msg => {
        if (msg.isRead) {
            list.forEach((item, index) => {
                if (item.id == msg.id) {
                    list[index].isRead = true;
                    return;
                }
            })
        } else {
            list.push(msg);
        }
        cb(null, list)
    });
    socket.emit('subscribeToMsg', userName);
}

// 发送消息
function sendMsg(data, cb) {

    socket.emit('clientSendMsg', data);
}

//开始订阅毫秒级随机消息
function subscribeInmsec(cb) {
    let allData = []
    for (let i = 0; i < num; i++) {
        allData.push({
            id: i,
            label: "ewr",
            value: "1234567890"
        })
    }
    socket.on('data', list => {
        list.forEach(item => {
            // console.log("接收到参数：", item)
            // let result = allData.find(data => {
            //     return data.id === item.id
            // })
            allData.forEach((data, index) => {
                if (data.id === item.id) {
                    allData[index] = item;
                    return;
                }
            })

        })
        cb(null, allData)
    });
    socket.emit('subscribeInmsec', interval, num);
}


export { subscribe, subscribeInmsec, sendMsg };